﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
using System.Net;
using System.Web;
using System.IO;

namespace MoGuJieSprider
{
    public partial class Form1 : Form
    {
        Dictionary<string, string> categories = new Dictionary<string, string>();

        string siteurl = "http://localhost:55555";

        int c = 0;
        string categoryId;
        int pagecount = 1;
        int min = 30;
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

            LoadCategories();

            //categories.Add("牛仔裤", "488EF19A-4B70-4D69-9C91-085E3291435E");
            //categories.Add("小背心/小吊带", "50E4B44E-8B49-4344-8F22-22E837EE217A");
            //categories.Add("连衣裙", "56135778-2AD0-4570-83AB-34DE371AA57C");
            //categories.Add("皮衣", "186639CE-3408-4E00-91FD-912C0058173B");
            //categories.Add("T恤", "68AACDCF-580E-4257-A453-A0438098880E");
            //categories.Add("短外套", "232A1686-EA21-4468-AC3A-ACFAF42D8925");
            //categories.Add("针织衫", "6C4F84A6-5683-4F61-9A84-C2717ED6DD47");
            //categories.Add("马夹", "FF95A9B0-81DB-4A33-ABB1-CB26B99270F4");
            //categories.Add("半身裙", "452A1B6B-A286-42B6-9895-EBA29F546E21");
            //categories.Add("短裤/热裤", "D5331341-0490-4396-896A-FAE59CEFAE87");
            //categories.Add("衬衫", "eda9f0b1-048c-47b0-9832-778352960695");
            //categories.Add("风衣", "1c5d97d5-6b49-45d4-a731-13c3c59ba4b1");
            //categories.Add("西装", "76a03b0d-6705-4b75-bb35-2e0661531888");
            //categories.Add("卫衣/绒衫", "f536ab2d-b6a2-4976-94eb-2340e63edf98");

            //foreach (var kv in categories)
            //{
            //    ComboBox_Categories.Items.Add(kv.Key);
            //}
        }

        private void Button_Load_Click(object sender, EventArgs e)
        {
            c = 0;
            categoryId = categories[ComboBox_Categories.SelectedItem.ToString()];
            Thread t = new Thread(new ParameterizedThreadStart(Dowork));
            Button_Load.Enabled = false;
            ComboBox_Categories.Enabled = false;
            pagecount = (int)numericUpDown1.Value;
            t.Start();


        }

        private void Dowork(object obj)
        {
            for (int i = 1; i <= pagecount; i++)
            {
                string html = HtmlBuilder.GetDataFromUrl(string.Format(TextBox_Url.Text, i));

                var items = HtmlBuilder.GetHtmlNodes(html, "//a[contains(@href,'/note/')]");




                if (items != null)
                {
                    var ajaxitems = AjaxItems(html);

                    if (ajaxitems != null)
                        foreach (var item in ajaxitems)
                        {
                            Publish(item);
                            Thread.Sleep(1000);
                        }
                    foreach (var item in items)
                    {

                        Publish(item);
                        Thread.Sleep(1000);
                    }
                }

                this.Invoke(new Action(() =>
                {
                    label2.Text = string.Format("第{0}页", i);
                }));
            }

            this.Invoke(new Action(() =>
            {
                Stop();
            }));

        }

        private void Publish(HtmlNode item)
        {
            string itemUrl = item.Attributes.ToList().Where(a => a.Name == "href").FirstOrDefault().Value;

            if (!itemUrl.Contains("http://www.mogujie.com"))
                itemUrl = "http://www.mogujie.com" + itemUrl;


            string itemHtml = HtmlBuilder.GetDataFromUrl(itemUrl);





            //var tags = HtmlBuilder.GetHtmlNodes(itemHtml, "//div[@class='piece_bd clearfix']/h2/span");

            //if (tags != null)
            //{
            //    foreach (var tag in tags)
            //    {
            //        var tagname = tag.InnerText.Trim();


            //        using (HeiBaiCaoDataContext context = new HeiBaiCaoDataContext())
            //        {
            //            var temp = context.HeiBaiCao_Tag.Where(t => t.name.ToLower() == tagname.ToLower()).FirstOrDefault();

            //            if (temp == null)
            //            {
            //                context.HeiBaiCao_Tag.InsertOnSubmit(new HeiBaiCao_Tag()
            //                {
            //                    id = Guid.NewGuid(),
            //                    name = tagname,
            //                    slug = tagname,
            //                    createtime = DateTime.Now,
            //                    goodscount = 0,
            //                    keys = tagname,
            //                    questioncount = 0
            //                });
            //                context.SubmitChanges();
            //            }

            //        }

            //    }

            //}









            string mid;

            string numiids = GetNumiids(itemUrl, out mid);


            string mogujieTitle = HtmlBuilder.GetHtmlNodes(itemHtml, "//title").FirstOrDefault().InnerText.Replace("蘑菇街", "").Replace("[图]", "").Replace("-", "").Replace("网友推荐单品：", "").Trim();


            string createUrl = string.Format("{0}/admin/goods/singlecreate?numiids={1}&categoryId={2}&mogujieTitle={3}&mid={4}&url={5}", siteurl, numiids, categoryId, mogujieTitle, mid, HttpUtility.UrlEncode(itemUrl));


            HttpStatusCode code;
            string result = HtmlBuilder.GetDataFromUrl(createUrl, out code);


            try
            {
                var idpic = HtmlBuilder.GetHtmlNodes(result, "//span").FirstOrDefault().InnerHtml;


                if (idpic.Contains("success"))
                {
                    var id = idpic.Replace("success$", "").Split('@')[0];
                    var pic = idpic.Replace("success$", "").Split('@')[1];

                    string fileext = "." + pic.Substring(pic.LastIndexOf(".") + 1);
                    string path = Path.Combine(Application.StartupPath, "Goods");
                    string filename = id + fileext;
                    path = path + "/" + filename;
                    WebClient myWebClient = new WebClient();
                    myWebClient.DownloadFile(pic, path);

                    string picUrl_180px = Path.Combine(Application.StartupPath, "Goods/Goods180PX/" + id + "_180.jpg");
                    Thumb.MakeThumbnail(path, picUrl_180px, 180, 75, "W");

                }
            }
            catch { }

            if (code != HttpStatusCode.OK)
            {

            }

            c++;
            label1.Invoke(new Action(() =>
            {
                label1.Text = c.ToString();
            }));
        }

        private HtmlNodeCollection AjaxItems(string html)
        {
            string pattern = "book:\"(?<C>.*?)\",lastTweetId:\"(?<I>.*?)\",";

            Regex r = new Regex(pattern);

            Match mc = r.Match(html);

            Dictionary<string, string> comments = new Dictionary<string, string>();

            string t = string.Empty;

            if (mc.Success)
            {
                string book = mc.Groups["C"].Value;
                string lastTweetId = mc.Groups["I"].Value;

                string ajaxUrl = string.Format("http://www.mogujie.com/book/ajax?book={0}&lastTweetId{1}", book, lastTweetId);

                t = HtmlBuilder.GetDataFromUrl(ajaxUrl);


                string bp = "\"book\":(?<C>.*?)\"}";

                r = new Regex(bp);

                Match mb = r.Match(t);

                if (mb.Success)
                {
                    string bookHtml = mb.Groups["C"].Value.Replace(@"\", "");
                    return HtmlBuilder.GetHtmlNodes(bookHtml, "//a[contains(@href,'/note/')]");
                }





            }
            return null;
        }



        private void LoadCategories()
        {
            string html = HtmlBuilder.GetDataFromUrl(siteurl + "/Admin/Category/List");

            var trs = HtmlBuilder.GetHtmlNodes(html, "//tr");
            ComboBox_Categories.Items.Clear();
            foreach (var tr in trs)
            {
                string id = tr.ChildNodes[1].InnerText.Trim();
                string name = tr.ChildNodes[3].InnerText.Trim();

                categories.Add(name, id);

                ComboBox_Categories.Items.Add(name);
            }

        }

        private string GetNumiids(string link, out string mid)
        {
            var ms = link.Replace("http://www.mogujie.com/note/", "").Split(new Char[] { '?' }, StringSplitOptions.RemoveEmptyEntries);

            mid = ms[0];

            string num_iids = string.Empty;

            string html = HtmlBuilder.GetDataFromUrl(link);

            var buy_url = HtmlBuilder.GetHtmlNodes(html, "//a[@class='shop_link']");


            if (buy_url != null)
            {
                string href = buy_url.FirstOrDefault().Attributes.ToList().Where(a => a.Name == "href").FirstOrDefault().Value;

                if (href.Contains("item.taobao.com"))
                {
                    href = System.Web.HttpUtility.UrlDecode(href);
                    Regex r = new Regex(@"&?id=(?<I>[\w\d]+)&?", RegexOptions.IgnoreCase);

                    Match m = r.Match(href);
                    if (m.Success)
                        num_iids = m.Groups["I"].Value;
                }
            }
            return num_iids;
        }

        private void Stop()
        {
            Button_Load.Enabled = true;
            ComboBox_Categories.Enabled = true;
        }
    }
}
